package com.cuitrip.business.home.arrange;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import com.cuitrip.apiservice.ServiceBusiness;
import com.cuitrip.apiservice.model.ApiManager;
import com.cuitrip.business.home.arrange.model.MonthCalendar;
import com.cuitrip.business.home.arrange.ui.MonthDateAdapter;
import com.cuitrip.business.home.arrange.ui.MonthHolderView;
import com.cuitrip.business.tripservice.TripEditActivity;
import com.cuitrip.component.popupmenu.PopupMenu;
import com.cuitrip.component.popupmenu.PopupMenuItem;
import com.cuitrip.component.statelayout.StateLayout;
import com.cuitrip.business.date.model.ServiceDateDetail;
import com.cuitrip.business.tripservice.model.ServiceInfo;
import com.cuitrip.service.R;
import com.lab.adapter.BaseHolderView;
import com.lab.adapter.HolderViewAdapter;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragment;
import com.lab.network.config.CtResponseCode;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.model.ProxyResult;
import com.lab.network.proxy.ApiProxy;
import com.lab.utils.ArrayUtil;
import com.lab.utils.MessageUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;

import butterknife.ButterKnife;
import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created on 7/23.
 */
public class ArrangeFragment extends CustomUiFragment implements IProxyCallback{

    private static final String TAG = "ArrangeFragment";

    @Bind(R.id.state_layout)
    StateLayout mStateLayout;

    @Bind(R.id.select_item)
    TextView selectItem;

    @Bind(R.id.select_icon)
    TextView selectView;

    @Bind(R.id.select_layout)
    View selectLayout;

    @Bind(R.id.arrange_list)
    ListView mListView;

    @Bind(R.id.update_layout)
    View updateLayout;

    @Bind(R.id.instruction_layout)
    View instructionLayout;

    private HolderViewAdapter mAdapter;

    private List<MonthCalendar> monthCalendarList = new ArrayList<>();

    private List<ServiceInfo> serviceList = new ArrayList<>();

    private List<Long> persistDateList = new ArrayList<>();
    private List<Long> mAvailableDateList = new ArrayList<Long>();
    private List<Long> mBookedDateList = new ArrayList<Long>();

    private ApiProxy mApiProxy = new ApiProxy(this);

    private String currentSid;
    private String timeZone;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState, R.layout.page_arrange);
    }

    public void initView() {
        ButterKnife.bind(this, getView());
        mAdapter = new HolderViewAdapter(getActivity(), monthCalendarList, MonthHolderView.class);
        mListView.setAdapter(mAdapter);
    }

    public void initData() {
        mStateLayout.changeState(StateLayout.State.Loading);
        getServiceList();
    }

    @Override
    public void initListener() {
        mStateLayout.setOnClickStateLayoutListener(new StateLayout.OnClickStateLayoutListener() {
            @Override
            public void onClick(StateLayout.State state) {
                showNoCancelDialog();
                getServiceList();
            }
        });
        mStateLayout.setAction(new StateLayout.Action() {
            @Override
            public void performEmptyAction() {
                if (getActivity() != null) {
                    TripEditActivity.navigate2CreateTripActivity(getHostActivity());
                }
            }
        });
    }

    private void inflateDate() {
        monthCalendarList.clear();
        Calendar todayCalendar = Calendar.getInstance();
        todayCalendar.setTimeZone(TimeZone.getTimeZone(timeZone));
        todayCalendar.set(Calendar.HOUR_OF_DAY, 0);
        todayCalendar.set(Calendar.MINUTE, 0);
        todayCalendar.set(Calendar.SECOND, 0);
        todayCalendar.set(Calendar.MILLISECOND, 0);

        Calendar maxCalendar = Calendar.getInstance();
        maxCalendar.setTimeZone(TimeZone.getTimeZone(timeZone));
        maxCalendar.set(Calendar.HOUR_OF_DAY, 0);
        maxCalendar.set(Calendar.MINUTE, 0);
        maxCalendar.set(Calendar.SECOND, 0);
        maxCalendar.set(Calendar.MILLISECOND, 0);
        maxCalendar.add(Calendar.DAY_OF_YEAR, 60);
        int showMonthCount = (maxCalendar.get(Calendar.YEAR) - todayCalendar.get(Calendar.YEAR)) * 12 + (maxCalendar.get(Calendar.MONTH) - todayCalendar.get(Calendar.MONTH));

        for (int i = 0; i <= showMonthCount; i++) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeZone(TimeZone.getTimeZone(timeZone));
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            calendar.add(Calendar.MONTH, i);
            monthCalendarList.add(new MonthCalendar(calendar));
        }

        mAdapter.setHolderViewCallback(new HolderViewAdapter.HolderViewCallback() {
            @Override
            public void onHolderViewInvalidate(BaseHolderView holderView, int position) {
                if (holderView instanceof MonthHolderView) {
                    MonthHolderView monthHolderView = (MonthHolderView) holderView;
                    monthHolderView.setAvailableDateList(mAvailableDateList);
                    monthHolderView.setBookDateList(mBookedDateList);
                    monthHolderView.setOnSelectChangeCallBack(new MonthDateAdapter.OnSelectChangeCallBack() {
                        @Override
                        public void onSelectRemove(Long time) {
                            if (mAvailableDateList.contains(time)) {
                                mAvailableDateList.remove(time);
                                updateCommitLayout(true);
                            }
                        }

                        @Override
                        public void onSelectAdd(Long time) {
                            mAvailableDateList.add(time);
                            updateCommitLayout(true);
                        }
                    });
                }
            }
        });

        mAdapter.notifyDataSetChanged();

    }

    private void updateCommitLayout(boolean isSelectChanged) {
        if (isSelectChanged) {
            instructionLayout.setVisibility(View.INVISIBLE);
            updateLayout.setVisibility(View.VISIBLE);
        } else {
            instructionLayout.setVisibility(View.VISIBLE);
            updateLayout.setVisibility(View.INVISIBLE);
        }

    }

    @OnClick(R.id.select_layout)
    public void selectList() {
        List<PopupMenuItem> popupMenuItemList = new ArrayList<PopupMenuItem>();
        for (ServiceInfo serviceInfo : serviceList) {
            popupMenuItemList.add(new PopupMenuItem(serviceInfo.getSid(), serviceInfo.getName()));
        }
        PopupMenu popupMenu = PopupMenu.getInstance(getActivity(), popupMenuItemList, new PopupMenu.PopupMenuCallback() {
            @Override
            public boolean onPopupMenuItemClick(int position, PopupMenuItem popupMenuItem) {
                updateSelectItem(serviceList.get(position));
                return false;
            }

            @Override
            public void onPopupMenuStateChanged(boolean isShow) {
                if (isShow) {
                    selectView.setText(getString(R.string.up_arrow_icon));
                } else {
                    selectView.setText(getString(R.string.down_arrow_icon));
                }
            }

        });
        popupMenu.show(selectLayout);

    }

    private void updateSelectItem(ServiceInfo serviceInfo) {
        selectItem.setText(serviceInfo.getName());
        this.currentSid = serviceInfo.getSid();
        requestDate(serviceInfo.getSid());
    }

    private void requestDate(String sid) {
        showLoading();
        ServiceBusiness.getServiceAvailableAndBookedDate(mApiProxy, sid);
    }

    private void addFilterCheckedServiceList(List<ServiceInfo> serviceInfos) {
        for (ServiceInfo serviceInfo : serviceInfos) {
            if (serviceInfo.isChecked()) {
                serviceList.add(serviceInfo);
            }
        }
    }

    @OnClick(R.id.action_cancel)
    public void revertDateSet() {
        mAvailableDateList.clear();
        mAvailableDateList.addAll(persistDateList);
        updateCommitLayout(false);
        mAdapter.notifyDataSetChanged();
        instructionLayout.setVisibility(View.VISIBLE);
        updateLayout.setVisibility(View.INVISIBLE);
    }

    @OnClick(R.id.action_save)
    public void commitDateSet() {
        showNoCancelDialog();
        ServiceBusiness.modifyServiceInfo(mApiProxy, currentSid, mAvailableDateList);
    }

    private void getServiceList() {
        ServiceBusiness.getServiceList(mApiProxy);
    }


    @Override
    public boolean initCloseTopBar() {
        return false;
    }

    @Override
    public CustomUiConfig initCustomUiConfig() {
        CustomUiConfig customUiConfig = new CustomUiConfig();
        customUiConfig.mTopbarMiddleAreaName = getString(R.string.main_nav_calendar);
        return customUiConfig;
    }

    @Override
    public boolean onProxyResult(ProxyResult<?> result) {
        CtApiResponse response = (CtApiResponse) result.getData();
        if (ApiManager.MODIFY_SERVICE_INFO.equals(response.getApiName())){
            handleModifyResult(response);
        }else if (ApiManager.SERVICE_LIST.equals(response.getApiName())){
            handleServiceListResult(response);
        } else if (ApiManager.GET_AVAILABLE_BOOK.equals(response.getApiName())){
            handleGetServiceDateDetailResult(response);
        }
        return false;
    }

    private void handleGetServiceDateDetailResult(CtApiResponse response){
        hideLoading();
        if (response!= null && response.code == CtResponseCode.RESULT_OK){
            if (response.result instanceof ServiceDateDetail) {
                ServiceDateDetail detail= (ServiceDateDetail) response.result;
                List<Long> availableDateList = detail.getAvailableDate();
                List<Long> bookedDateList = detail.getBookedDate();
//                timeZone = detail.getTimeZone();
                timeZone = "GMT +000";
//                MonthDateAdapter adapter = MonthDateAdapter.getAdapter();
//                if ( adapter !=null){
//                    adapter.setTimeZone(timeZone);
//                }
//                if (availableDateList != null && bookedDateList != null) {
//                    availableDateList.removeAll(bookedDateList);
//                }
                mAvailableDateList.clear();
                mBookedDateList.clear();
                mAvailableDateList.addAll(availableDateList);
                mBookedDateList.addAll(bookedDateList);

                persistDateList.clear();
                persistDateList.addAll(availableDateList);

                updateCommitLayout(false);
                inflateDate();
            }
        }else{
            if (response.code == 105 && true) {//可约日期为空
                return;
            }
            MessageUtils.showToast(response.msg);
        }
    }


    private void handleModifyResult(CtApiResponse response){
        hideNoCancelDialog();
        if (response!= null && response.code == CtResponseCode.RESULT_OK){
            instructionLayout.setVisibility(View.VISIBLE);
            updateLayout.setVisibility(View.INVISIBLE);
//            MessageUtils.showToast(R.string.calendar_operation_update_feedback_suc);
        }else{
            if (response != null && !TextUtils.isEmpty(response.msg)) {
                MessageUtils.showToast(response.msg);
            }
        }
    }


    private void handleServiceListResult(CtApiResponse response){
        hideNoCancelDialog();
        if (response!= null && response.code == CtResponseCode.RESULT_OK){
            if (response.result instanceof List) {
                List<ServiceInfo> serviceInfos = (List<ServiceInfo>) response.result;
                if (ArrayUtil.isNullOrEmpty(serviceInfos)) {
                    mStateLayout.changeState(StateLayout.State.Empty);
                } else {
                    serviceList.clear();
                    addFilterCheckedServiceList(serviceInfos);
                    if (serviceList.isEmpty()) {
                        mStateLayout.changeState(StateLayout.State.Empty);
                    } else {
                        mStateLayout.changeState(StateLayout.State.INIT);
                        updateSelectItem(serviceList.get(0));
                    }

                }
            }
        }else{
            if (response != null && !TextUtils.isEmpty(response.msg)) {
                MessageUtils.showToast(response.msg);
            }
            mStateLayout.changeState(StateLayout.State.Empty);
        }
    }

}
